const Controller = require('../core/base_controller');


class UserController extends Controller {

  async area_info() {
    const { ctx, ctx: { service, customBody }, app, app: { mysql } } = this;
    var area_info = await mysql.select('area_info')
    this.success({
      code: 200,
      data: area_info
    })

  }
  async getopenid() {
    const { ctx, ctx: { service, customBody }, app, app: { mysql } } = this;

    var url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.wxappid}&secret=${this.wxsecret}&js_code=${customBody.code}&grant_type=authorization_code`;
    const result = await app.curl(url, {
      contentType: 'json',
    });
    var jsonstring = result.data.toString()
    var jsonobject = JSON.parse(jsonstring)
    customBody.session_key = jsonobject.session_key
    const res = await ctx.service.decrypt.find(customBody, this)
    this.success({
      code: 200,
      data: jsonobject,
      ...res
    })
  }
  async getPhoneNumber() {
    const { ctx, ctx: { service, customBody }, app, app: { mysql } } = this;
    const res = await ctx.service.decrypt.find(customBody, this)
    var { phoneNumber } = res
    var data = {
      telnum: phoneNumber,
      avatarurl: customBody.avatarUrl,
      openid: customBody.openid,
      gender: customBody.gender,
      city: customBody.city,
      province: customBody.province,
      nickname: customBody.nickName,
      country: customBody.country
    }
    var user = await mysql.select('wx_user', { where: { telnum: phoneNumber } })
    if (user.length > 0) {
      data.id = user.id
      await mysql.update('wx_user', { ...data })

    } else {
      console.log(data)
      await mysql.insert('wx_user', data);

    }
    user = await mysql.select('wx_user', { where: { telnum: phoneNumber } })



    this.success({
      code: 200,
      data: user[0]
    })


  }

}


module.exports = UserController;
